import React, { useState, useEffect } from 'react';
import style from './Coupons.module.css'
import { Button, Table, Select, Input, Modal, message } from 'antd';
import { useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import CreateExcel from 'js-export-excel';
import Store from "./../../store/index"
import * as actions from "./../../store/actions/marketing/index"

const CouponsView = () => {
    const [messageApi, contextHolder] = message.useMessage();
    const [columns, setColumns] = useState([
        {
            title: 'ID',
            dataIndex: 'id'
        },
        {
            title: '优惠劵名称',
            dataIndex: 'name',
        },
        {
            title: '优惠内容',
            dataIndex: 'content',
        },
        {
            title: '类型',
            dataIndex: 'type',
        },
        {
            title: '已领取',
            dataIndex: 'Claimed',
        },
        {
            title: '剩余',
            dataIndex: 'remainder',
        },
        {
            title: '状态',
            dataIndex: 'state',
        },
        {
            title: '操作',
            dataIndex: '',
            width: '152px',
            render: (text) => (
                <div>
                    {contextHolder}
                    <Button type="link" onClick={() => edit(text)}>编辑</Button>
                    <Button type="link" onClick={() => shanChu(text)}>删除</Button>
                </div>
            )
        }
    ])
    const [data, setData] = useState(Store.getState().marketing.user)
    // console.log(Store.getState().marketing.user)
    const shanChu = (b) => {
        Modal.confirm({
            title: '删除',
            icon: <ExclamationCircleOutlined />,
            content: '您确定要删除吗？',
            okText: '确认',
            cancelText: '取消',
            onOk() {
                data.forEach((el, index) => {
                    if (el.key === b.key) {
                        data.splice(index, 1)
                        const arr = [...data]
                        setData(arr)
                    }
                })
                messageApi.open({
                    type: 'success',
                    content: '删除成功',
                });
            },
            onCancel() {
                messageApi.open({
                    type: 'error',
                    content: '删除失败',
                });
            }
        })
    }
    const [size, setSize] = useState('large');
    const [option1, setOption1] = useState([
        {
            value: '0',
            label: '全部',
        },
        {
            value: '1',
            label: '满减券',
        },
        {
            value: '2',
            label: '折扣券',
        },
    ])
    const [option2, setOption2] = useState([
        { value: '0', label: '全部' },
        { value: '1', label: '未开始' },
        { value: '2', label: '进行中' },
        { value: '3', label: '已结束' }
    ])
    const inRef = useRef()
    let [select1, setSelect1] = useState('')
    let [select2, setSelect2] = useState('')
    const handleChange1 = (e) => {
        setSelect1(option1[e].label)
    }
    const handleChange2 = (e) => {
        setSelect2(option2[e].label)
    }
    const [copy, setCopy] = useState([])
    useEffect(() => {
        setCopy([...data])
    }, []);
    const Search = () => {
        // console.log(inRef.current.input.value, select1, select2)
        let a = inRef.current.input.value
        let b = select1
        let c = select2
        let arr = []
        if (b === '全部') {
            b = ''
        }
        if (c === '全部') {
            c = ''
        }
        copy.forEach(el => {
            const condition = (!a || el.name.includes(a)) &&
                (!b || el.type.includes(b)) && (!c || el.state.includes(c))
            if (condition) {
                arr.push(el)
            }
        })
        if (a === '' && b === '' && c === '') {
            arr = [...copy]
        }
        setData(copy)
        setData(arr)
    }
    const navigate = useNavigate()
    const addTo = () => {
        navigate('CouponsCV', { state: { title: '新建优惠券', txFb: true } })
    }
    const edit = (obj) => {
        console.log(obj)
        obj.title = '编辑优惠券'
        obj.txFb = false
        navigate('CouponsCV', { state: obj })
    }
    const download = () => {
        let a = {}
        let dataTable = []
        a.fileName = '优惠券';
        data.map(el => {
            dataTable.push({
                'ID': el.id,
                '优惠劵名称': el.name,
                '优惠内容': el.content,
                '类型': el.type,
                '已领取': el.Claimed,
                '剩余': el.remainder,
                '状态': el.state
            })
        });
        a.datas = [
            {
                sheetData: dataTable,
                sheetName: 'sheet',
                sheetFilter: ["ID", "优惠劵名称", "优惠内容", "类型", "已领取", "剩余", "状态"],
                sheetHeader: ["ID", "优惠劵名称", "优惠内容", "类型", "已领取", "剩余", "状态"],
            }
        ];
        let toExcel = new CreateExcel(a);
        toExcel.saveExcel()
    }
    const location = useLocation()
    return (
        <div>
            <div className={style.box}>
                <Button type="primary" size={size} onClick={addTo}>新建优惠券</Button>
            </div>
            <div className={style.box2}>
                <div className={style.shuRu}>
                    <div>
                        <span className={style.mc}>名称</span>
                        <Input placeholder="请输入名称" style={{ width: 201 }} ref={inRef} />
                    </div>
                    <div>
                        <span className={style.mc}>类型</span>
                        <Select
                            showSearch
                            style={{
                                width: 166,
                            }}
                            onChange={handleChange1}
                            placeholder="请选择类型"
                            optionFilterProp="children"
                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                            filterSort={(optionA, optionB) =>
                                (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
                            }
                            options={option1}
                        />
                    </div>
                    <div>
                        <span className={style.mc}>状态</span>
                        <Select
                            showSearch
                            style={{
                                width: 166,
                            }}
                            onChange={handleChange2}
                            placeholder="请选择类型"
                            optionFilterProp="children"
                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                            filterSort={(optionA, optionB) =>
                                (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
                            }
                            options={option2}
                        />
                    </div>
                </div>
                <div className={style.an}>
                    <Button style={{ width: 89 }} type="primary" size={size} onClick={Search}>搜索</Button>
                    <Button style={{ width: 89 }} size={size} onClick={download}>导出</Button>
                </div>
            </div>
            <div className={style.box3}>
                <Table columns={columns} dataSource={data} pagination={{ pageSize: 5, total: data.length, showTotal: total => `共${total}条`, showQuickJumper: true }} />
            </div>
        </div>
    );
}

export default CouponsView;
